package cmd

import (
	"card-platform/config"
	"card-platform/control"
	"card-platform/model"
	"github.com/gin-gonic/gin"
	"github.com/jasonlvhit/gocron"
	"github.com/spf13/cobra"
	"github.com/unrolled/secure"
	"pkg/cfg"
)

func TlsHandler() gin.HandlerFunc {
	return func(c *gin.Context) {
		secureMiddleware := secure.New(secure.Options{
			SSLRedirect: true,
			SSLHost:     config.Address,
		})
		err := secureMiddleware.Process(c.Writer, c.Request)
		if err != nil {
			return
		}
		c.Next()
	}
}

var startCmd = &cobra.Command{
	Use:   "start",
	Short: "启动服务",
	Run: func(cmd *cobra.Command, args []string) {
		config.InitConfig()
		err := model.InitDb(config.MysqlDsn)
		if err != nil {
			cfg.LogErr(err.Error())
		}

		go RecycleTask()

		r := gin.Default()
		r.Use(control.Cors())
		gin.SetMode("debug")
		r.Static("doc", config.GetRootPath()+"/doc")
		r.Static("upload", config.GetRootPath()+"/upload")
		control.SetRouter(r)
		r.Run(config.Address)
		return
	},
}

func init() {
	rootCmd.AddCommand(startCmd)
}

func RecycleTask() {

	s := gocron.NewScheduler()
	s.Every(1).Minute().Do(control.Recycle)
	sc := s.Start() // keep the channel
	<-sc
}
